package com.shqcjd.yunweiyanoperator.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.pojo.CollectionBean;
import com.shqcjd.yunweiyanoperator.model.pojo.RepairRecordBean;
import com.shqcjd.yunweiyanoperator.model.pojo.VideoCategory;
import com.shqcjd.yunweiyanoperator.ui.activity.remote.RemoteFileListActivity;
import com.shqcjd.yunweiyanoperator.ui.adapter.RepairRecordAdapter;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.Config;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.WrapContentLinearLayoutManager;
import com.shqcjd.yunweiyanoperator.widget.LoginTipsDialog;
import com.shqcjd.yunweiyanoperator.widget.ShareDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 维修记录
 */
public class RepairRecordActivity extends BaseActivity {

    @BindView(R.id.rv_repair_record)
    RecyclerView rvRepairRecord;
    @BindView(R.id.sr_repair_record)
    SwipeRefreshLayout srRepairRecord;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.btn_finish)
    ImageView btnFinish;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_search)
    EditText etSearch;

    List<RepairRecordBean.ListBean> mList = new ArrayList<>();
    private Context mContext;
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    private RepairRecordAdapter repairRecordAdapter;
    private int pageSize;
    private final int PAGE_TOTAL = Config.PAGE_TOTAL;
    private ShareDialog shareDialog;
    private LoginTipsDialog loginTipsDialog;
    private String keyword = "";
    private List<VideoCategory> videTypeList = new ArrayList<>();

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_repair_record;
    }

    @Override
    public void init() {
        super.init();
        mContext = this;
    }

    @Override
    public void initView() {
        super.initView();
        tvTitle.setText("维修记录");

        refreshData();
        getVodepCategoryHttp();
        srRepairRecord.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                keyword = editable.toString();
                refreshData();
            }
        });
    }

    private void refreshData() {
        refreshOrLoadMore();
        srRepairRecord.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        mList.clear();
        getDataList(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getDataList(page + 1);
    }

    private void refreshOrLoadMore() {
        if (repairRecordAdapter != null) {
            repairRecordAdapter.notifyLoadMoreToLoading();
        }
    }


    private void getDataList(int p) {
        Map<String, String> map = new HashMap<>();
        map.put("acceptUserName", keyword);
        map.put("page", p + "");
        map.put("size", PAGE_TOTAL + "");
        ApiService.repairRecord(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<RepairRecordBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<RepairRecordBean> responseData) {
                        if (responseData.retCode != 10000) {
                            return;
                        }
                        mList.addAll(responseData.data.list);
                        pageSize = responseData.data.list.size();
                        if (repairRecordAdapter == null) {
                            rvRepairRecord.setLayoutManager(new WrapContentLinearLayoutManager(mContext));
                            repairRecordAdapter = new RepairRecordAdapter(mList, mContext);
                            rvRepairRecord.setAdapter(repairRecordAdapter);
                            repairRecordAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                @Override
                                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                    if(view.getId() == R.id.tv_view_file){
                                        Intent it = new Intent(mContext, RemoteFileListActivity.class);
                                        it.putExtra("channelID", mList.get(position).roomId);
                                        it.putExtra("guideOrRepair", 1);
                                        startActivity(it);
                                    }else if(view.getId() == R.id.tv_view_share){
                                        if(mList.get(position).shared==1){
                                        }else{
                                            shareDialog = new ShareDialog(mContext);
                                            shareDialog.setOnClickDialogListener(new ShareDialog.setOnClickDialogListener() {
                                                @Override
                                                public void onClickAdd(String info, String mTypeId, String remark) {
                                                    shareHttp(position, info, mTypeId, remark);
                                                }
                                            });
                                            shareDialog.show();
                                            shareDialog.setVideoData(videTypeList);
                                            shareDialog.setTitle(mList.get(position).title);
                                        }
                                    }
                                }
                            });
                            repairRecordAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                @Override
                                public void onLoadMoreRequested() {
                                    rvRepairRecord.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (PAGE_TOTAL > pageSize) {
                                                rvRepairRecord.post(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        repairRecordAdapter.loadMoreEnd();
                                                    }
                                                });
                                            } else {
                                                loadMoreData();
                                            }
                                        }
                                    });
                                }
                            });
                        }
                        if (isRefreshOrLoadMore == 1) {
                            page = page + 1;
                            repairRecordAdapter.loadMoreComplete();
                        }
                        if (mList.size() == 0) {
                            rlIsnull.setVisibility(View.VISIBLE);
                        } else {
                            rlIsnull.setVisibility(View.INVISIBLE);
                        }
                        repairRecordAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srRepairRecord.setRefreshing(false);
                    }
                });
    }

    private void shareHttp(int pos, String title, String mTypeId, String remark){
        Map<String, String> map = new HashMap<>();
        map.put("maintainRecordId", mList.get(pos).id+"");
        map.put("title", title);
        map.put("videoCategoryId", mTypeId);
        if(mTypeId.equals("-1")){
            map.put("videoCategoryName", remark);
        }
        ApiService.createShare(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData.retCode == 10000) {
                            shareDialog.cleanData();
                            shareDialog.dismiss();
                            mList.get(pos).shared=1;
                            repairRecordAdapter.notifyItemChanged(pos);
                            ToastUtils.showShort(mContext,"分享成功");
                        } else {
                            ToastUtils.showShort(mContext,retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext,errorMessage);
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                    }
                });
    }

    private void getVodepCategoryHttp(){
        ApiService.getVideoCategory()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<VideoCategory>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<VideoCategory>> retData) {
                        if (retData.retCode == 10000) {
                            videTypeList = retData.data;
                        } else {
                            ToastUtils.showShort(mContext,retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext,errorMessage);
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                    }
                });
    }

    @OnClick(R.id.btn_finish)
    public void onViewClicked() {
        finish();
    }
}
